﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using System;
using Common;

/// <summary>
/// 用来管理跟服务器数据Socket连接
/// </summary>
public class ClientManager : BaseManager
{
    private const string IP = "192.168.1.4";
    private const int PORT = 6688;

    private Socket clientSocket;
    private Message msg = new Message();

    public ClientManager(GameFacade _facade) : base(_facade)
    {

    }

    public override void OnInit()
    {
        base.OnInit();

        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            clientSocket.Connect(IP, PORT);
            Start();
        }
        catch (Exception e)
        {
            Debug.LogWarning("无法连接到服务器，请检查您的网络！！" + e);
        }
    }

    /// <summary>
    /// 开始监听
    /// </summary>
    private void Start()
    {
        clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.ReaminSize, SocketFlags.None, ReceiveCallback, null);
    }

    /// <summary>
    /// 回调
    /// </summary>
    /// <param name="ar"></param>
    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            if (clientSocket == null || clientSocket.Connected == false)
                return;
            int count = clientSocket.EndReceive(ar);
            //消息处理
            msg.ReadMessage(count, OnProcessDataCallback);

            Start();
        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
    }

    private void OnProcessDataCallback(ActionCode actionCode, string data)
    {
        facade.HandleResponse(actionCode, data);
    }

    /// <summary>
    /// 向服务器端发送请求
    /// </summary>
    /// <param name="requestCode"></param>
    /// <param name="actionCode"></param>
    /// <param name="data"></param>
    public void SendRequest(RequestCode requestCode, ActionCode actionCode, string data)
    {
        byte[] bytes = Message.PackData(requestCode, actionCode, data);
        clientSocket.Send(bytes);
    }

    public override void OnDestroy()
    {
        base.OnDestroy();
        try
        {
            if (clientSocket != null)
                clientSocket.Close();
        }
        catch (Exception e)
        {
            Debug.LogWarning("无法关闭跟服务器的连接！！" + e);
        }
    }
}
